package com.dongdongshop.mq;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.SeckillContant;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.service.SeckillOrderService;
import com.dongdongshop.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "seckill-goods",topic = "seckill-goods-topic")
public class SeckillGoodsConsumer implements RocketMQListener<JSONObject>{

    @Autowired
    private IdWorker      idWorker;
    @Autowired
    private RedisTemplate       redisTemplate;
    @DubboReference
    private SeckillOrderService seckillOrderService;
    @Override
    public void onMessage(JSONObject jsonObject) {
        /*
        *  jsonObject.put("id",id);
        jsonObject.put("userName",name);
        * */
        Integer id = (Integer) jsonObject.get("id");
        String userName = (String)jsonObject.get("userName");
        //获取所以秒杀商品
        TbSeckillGoods seckillGoods = (TbSeckillGoods)redisTemplate.boundHashOps(SeckillContant.SECKILL).get(Long.valueOf(id));
        //生成订单
        long orderId = idWorker.nextId();
        TbSeckillOrder order = new TbSeckillOrder();
        order.setId(orderId);//订单id
        order.setSeckillId(seckillGoods.getId());//商品id
        order.setMoney(seckillGoods.getCostPrice());//支付金额
        order.setUserId(userName);//用户名
        order.setCreateTime(new Date());//订单创建时间
        order.setStatus("1");//订单状态:1待支付
        order.setSellerId(seckillGoods.getSellerId());//商家
        seckillOrderService.addOrderBefore(order);
    }
}
